package com.imooc.demo.controller;

import com.imooc.demo.entity.Admin;
import com.imooc.demo.entity.Result;
import com.imooc.demo.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;

    /**
     * 1.登录
     */
    @RequestMapping("/login.do")
    @ResponseBody
    public Result login(HttpServletRequest request, Admin admin) {
        Result result = null;
        try {
            result = adminService.login(admin);// 如果登录成功返回 含有Id 的User
            if (result.isSuccess()) {
                //将user保存到session中
                request.getSession().setAttribute("admin", admin);
            }
        } catch (Exception e) {
            result = new Result(false, "登录失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 2.根据id查询用户信息
     */
    @RequestMapping("/getAdminById.do")
    @ResponseBody
    public Admin getUserById(String id) {
        Admin admin = null;
        try {
            admin = adminService.getAdminById(id);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return admin;
    }

    /**
     * 3.注销
     */
    @RequestMapping("/logoutAdmin.do")
    @ResponseBody
    public void logoutAdmin(HttpServletRequest request) {
        try {
            request.getSession().removeAttribute("admin");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
